package com.fat.controller;

import com.fat.entity.Goods;
import com.fat.service.IGoodsService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController extends BaseController {

    @Autowired
    private IGoodsService goodsService;

    @PostMapping
    public ResponseEntity add(@RequestBody Goods goods) {
        boolean saved = goodsService.save(goods);
        return saved ? success("创建成功", null) : error("创建失败");
    }

    @GetMapping("/{id}")
    public ResponseEntity getById(@PathVariable Long id) {
        Goods goods = goodsService.getById(id);
        return goods != null ? success(goods) : error("未找到对应记录");
    }

    @PutMapping
    public ResponseEntity update(@RequestBody Goods goods) {
        boolean updated = goodsService.updateById(goods);
        return updated ? success("更新成功", null) : error("更新失败");
    }

    @DeleteMapping("/{id}")
    public ResponseEntity delete(@PathVariable Long id) {
        boolean deleted = goodsService.removeById(id);
        return deleted ? success("删除成功", null) : error("删除失败");
    }

    @GetMapping("/list")
    public ResponseEntity list() {
        List<Goods> list = goodsService.list();
        return success(list);
    }

    @GetMapping("/page")
    public ResponseEntity page(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                              @ModelAttribute Goods goods) {
        // 创建分页对象
        Page<Goods> page = new Page<>(pageNum, pageSize);
        
        // 创建查询条件
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        // 如果实体对象不为null，则根据实际情况添加查询条件
        if (goods != null) {
            // 
            if (goods.getId() != null) {
                queryWrapper.eq(Goods::getId, goods.getId());
            }
            // 
            if (goods.getName() != null) {
                queryWrapper.eq(Goods::getName, goods.getName());
            }
            // 
            if (goods.getPrice() != null) {
                queryWrapper.eq(Goods::getPrice, goods.getPrice());
            }
            // 
            if (goods.getCreateTime() != null) {
                queryWrapper.eq(Goods::getCreateTime, goods.getCreateTime());
            }
        }
        
        // 执行分页查询
        page = goodsService.page(page, queryWrapper);
        return success(page);
    }
}